// 表单头点击排序功能
// 依赖urly.js jquery.js
// 目标DOM属性data-current data-up data-sortb data-down
// 目标DOMclass table-sort table-sort-up table-sort-down
var urly = function(href){
    this.href = '';//完整路径
    this.href2 = '';//根路径
    this.paramsString = '';
    this.params = {};

    this.setHref = function(){
      return this
    }

    this.getHref = function(){
      return this.href;
    }

    this.setParams = function(params){
      var key;

      for(key in params){
        if(key != '' && key != undefined && params[key] != '' && params[key] != undefined){
          this.params[key] = params[key];
        }
        if(this.params[key] != undefined && params[key] == '' || params[key] == undefined){
          delete this.params[key];
        }
      }
      var p = '';
      var i = 0;
      //console.log(this.params)
      for(key in this.params){
        if(key != '' && key != undefined){
          if(i==0){
            p = p + key + '=' + this.params[key];
          } else {
            p = p + '&' + key + '=' + this.params[key];
          }
          i++;
        }
      }
      this.paramsString = p;
      this.href = this.href2 + '?' + this.paramsString;

      return this
    }

    this.init = function(href){

      this.href = href;
      if(this.href.indexOf('?')>=0){
        this.paramsString = this.href.split('?')[1];
        this.href2 = this.href.split('?')[0];
      } else {
        this.href2 = href;
      }
      this.parseParams();
      return this
    }

    //return array
    this.parseParams = function(){
      var par = this.paramsString.split('&');
      var size = par.length;

      while(size--){
        //console.log(size);
        var p = par[size];
        //console.log(p)
        p = p.split('=');
        this.params[p[0]] = decodeURI(p[1]?p[1]:'');
      }

      return this

    }

    this.getParams = function(){
      return this.params;
    }
    this.init(href);
  }

var u = new urly(window.location.href)

$('.table-sort').each(function(){
  var name = $(this).data('name')
  var up = $(this).data('up')
  var down = $(this).data('down')
  var current = $(this).data('current')

  var params = u.getParams()

  if(typeof params[name] != 'undefined'){
    $(this).attr('data-current', params[name])
    //$(this).addClass('table-sort-' + params[name])
    if(params[name] == up){
      $(this).addClass('table-sort-up')
    }
    if(params[name] == down){
      $(this).addClass('table-sort-down')
    }
  } else {
    //$(this).addClass('table-sort-')
  }
})

$('.table-sort').click(function(){
  var current = $(this).attr('data-current')
  var name = $(this).attr('data-name')
  var up = $(this).attr('data-up')
  var down = $(this).attr('data-down')
  var params = {}

//  alert(current)

  if(current == up){
    current = down
  } else {
    current = up
  }

  //alert(current)



  $('.table-sort').each(function(){
    params[name] = current
  })



  u.setParams(params)

  window.location.href = u.getHref()
})
